/*
 * @Author: fhw
 * @Date: 2022-07-07 11:35:09
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-02-02 17:11:17
 * @Description: 文章编辑
 */
import { errorTips } from '@/utils'
import { isTrue } from '@/utils/tools'
import { notification } from 'ant-design-vue'
import { equals, isNil } from 'ramda'
import { defineComponent, reactive, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import Panel from './components/panel'
import './style.scss'
enum DoType {
	draft = 'DRAFT',
	publish = 'PUBLISH',
}
export interface ArticleInfo {
	id?: number | null
	title?: string
	abstract?: string
	tags?: string[]
	category?: string
	content?: string
	imageUrl?: string
	type?: DoType
	status?: number
	categoryId?: string | null
	categoryName?: string
}
export default defineComponent({
	name: 'Editor',
	setup() {
		const router = useRouter()
		const route = useRoute()
		const loading = ref(false)
		const userId = localStorage.getItem('userId') as string
		watch(
			() => route.query,
			() => {
				if (isNil(route.query.id)) return
				init()
			},
			{
				immediate: true,
			}
		)
		/** 初始化 */
		async function init() {
			loading.value = true
			const { success, data } = await API.blog.article.getArticleInfo.request({ id: route.query.id })
			if (success) {
				loading.value = false
				pageState.id = data.data.id
				pageState.title = data.data.title
				pageState.content = data.data.content
				pageState.category = data.data.category
				pageState.tags = data.data.tags
				pageState.imageUrl = data.data.imageUrl
				pageState.status = data.data.status
			}
		}
		const panelVisible = ref(false)
		const pageState = reactive<ArticleInfo>({
			content: '',
			title: '',
			category: '',
			tags: [],
			imageUrl: '',
			status: 0,
			type: DoType.draft,
		})
		/** 发布文章 */
		async function onSubmit(data: any) {
			const title = !isTrue(pageState.title) ? '无标题' : pageState.title
			if (equals(pageState.type, DoType.publish)) {
				if (!isTrue(pageState.title)) {
					errorTips('请填写标题')
					return
				}
				if (!isTrue(pageState.content)) {
					errorTips('请填写文章内容')
					return
				}
			}
			const { success } = await API.blog.article.createUpdateArticle.request({
				...data,
				status: equals(pageState.type, DoType.draft) ? 0 : 1,
				title,
				content: pageState.content,
				id: pageState.id,
				category: data.categoryName ?? data.category,
				userId,
			})
			if (success) {
				const description = equals(pageState.type, DoType.draft) ? '保存草稿成功' : '发布成功,等待3秒跳转文章页'
				notification.success({
					message: '提示',
					description,
				})
				if (equals(pageState.type, DoType.draft)) return
				setTimeout(() => {
					router.push('/article')
				}, 3000)
			}
		}
		/** 图片上传 */
		async function handleUploadImage(event: any, insertImage: any, files: any) {
			const curFiles = files[0]
			const formData = new FormData()
			if (isNil(curFiles)) return
			formData.append('file', curFiles)
			const { success, data } = await API.blog.upload.uploadOSS.request({ data: formData })
			if (success) {
				insertImage({
					url: data.url,
					desc: curFiles.name,
				})
			}
		}
		return () => (
			<div id="editor">
				<header>
					<a-input
						v-model={[pageState.title, 'value']}
						class="editor-title"
						placeholder="输入文章标题..."
						maxlength={80}
					></a-input>
					<div class="right-box flexBox">
						{equals(pageState.status, 0) && (
							<a-button
								onClick={() => {
									pageState.type = DoType.draft
									onSubmit(pageState)
								}}
							>
								保存草稿
							</a-button>
						)}
						<a-button
							type="primary"
							onClick={() => {
								panelVisible.value = true
								pageState.type = DoType.publish
							}}
						>
							{equals(pageState.status, 0) ? '发布' : '更新'}
						</a-button>
						<Panel
							visible={panelVisible.value}
							dataSource={pageState}
							onClose={() => {
								panelVisible.value = false
							}}
							onSubmit={(data) => {
								onSubmit(data)
							}}
						/>
					</div>
				</header>
				<v-md-editor
					// 开启手动上传
					disabledMenus={[]}
					v-model={pageState.content}
					height="calc(100% - 64px)"
					onUploadImage={handleUploadImage}
				></v-md-editor>
			</div>
		)
	},
})
